import React, { useEffect, useRef, useState } from 'react';
import md5 from 'crypto-js/md5'
import { message } from 'antd'
import storage from '@/utils/storage';

const userid = '39c466361d'
const secretkey = 'aKz9jG6vxW'
const writeToken = 'b0116596-2260-42a4-be76-0e40ed894f8e'


function getSignData() {
  const ptime = new Date().getTime()
  console.log(ptime);
  const hash = md5(ptime + writeToken)
  const sign = md5(secretkey + ptime)
  return {
    ptime: ptime,
    hash: hash,
    sign: sign,
    userid: userid
  }
}

const videoUpload = () => new window.PlvVideoUpload({
  partSize: 1 * 1024 * 1024,
  // region: "line1", // (可选)上传线路, 默认line1
  events: {
    Error: function (err) {
      message.error(err?.message || '初始化失败')
      // 错误事件回调
      console.log(err);
    },
    UploadComplete: function () {
      // 全部上传任务完成回调
      console.log('上传完毕')
    },
  },
});

export type usePlvUploadProps = {
  onChange?: (fileList: any[], file: any,) => void;
  onSuccess?: (file: any,) => void;
  getPlvAuth?: () => any;
  refreshPlvAuth?: () => any;
}

// const usePlvVideoUpload = () => {
//   const videoUploadInstace = videoUpload();
//   return {videoUpload:videoUploadInstace }
// }
export const usePlvUpload = ({ onChange, onSuccess, getPlvAuth, refreshPlvAuth, }: usePlvUploadProps) => {
  const PlvUploaderRef = useRef<any>();
  const updateTimer = useRef<any>();
  const handleChange = (uploadInfo) => {
    onChange?.(PlvUploaderRef.current?.fileQueue?._list?.map(item => item.file), uploadInfo?.fileData?.file)
  }
  const handSuccess = (uploadInfo) => {
    onSuccess?.(uploadInfo?.fileData?.file)
  }
  const updateUserData = async (init = false) => {
    const data = init ? await getPlvAuth?.() : await refreshPlvAuth?.();
    PlvUploaderRef.current?.updateUserData(data);
    updateTimer.current = setTimeout(updateUserData, 1000 * 60 * 2)
  }
  // https://help.polyv.net/index.html#/vod/upload_js/web_upload_sdk
  const addFile = (file) => {
    const fileSetting = { // 文件上传相关信息设置
      title: file.name, // 标题
      desc: 'jssdk插件上传', // 描述
      cataid: '', // 上传分类目录ID
      tag: '', // 标签
      luping: 0, // 是否开启视频课件优化处理，对于上传录屏类视频清晰度有所优化：0为不开启，1为开启
      keepsource: 0, // 是否源文件播放（不对视频进行编码）：0为编码，1为不编码
      state: '' //用户自定义信息，如果提交了该字段，会在服务端上传完成回调时透传返回。
    }
    console.log(file.uid, 'uid');
    const uploadManager = PlvUploaderRef.current._addFile(
      file, // file 为待上传的文件对象
      {
        FileStarted: function (uploadInfo) { // 文件开始上传回调
          console.log("文件上传开始: " + uploadInfo.fileData.title);
        },
        FileProgress: function (uploadInfo) { // 文件上传过程返回上传进度信息回调

          uploadInfo.fileData.file.status = 'uploading';
          uploadInfo.fileData.file.percent = Math.ceil(uploadInfo.progress * 100);
          handleChange(uploadInfo);
          console.log("文件上传中: " + uploadInfo.fileData.file.percent.toFixed(2) + '%');
        },
        FileStopped: function (uploadInfo) { // 文件暂停上传回调
          uploadInfo.fileData.file.status = 'stop';
          handleChange(uploadInfo);
          console.log("文件上传停止: " + uploadInfo.fileData.title);

        },
        FileSucceed: function (uploadInfo, a) { // 文件上传成功回调
          // uploadInfo.file.status = 'done';
          const { file, ...response } = uploadInfo.fileData
          uploadInfo.fileData.file.response = response;
          uploadInfo.fileData.file.status = 'done';
          uploadInfo.fileData.file.percent = 100;
          handleChange(uploadInfo);
          handSuccess(uploadInfo)

          // 上传成功手动清除本地保利威缓存，解决同一文件读取本地存储的，导致UploadID错误
          if (uploadManager.id) {
            storage.remove(`hw_${uploadManager.id}`)
          }
          console.log("文件上传成功: " + uploadInfo.fileData.title);
          console.log(uploadManager.id, 'uploadManager.id')
          //console.log("文件上传成功: " + uploadInfo.fileData.title);

        },
        FileFailed: function (uploadInfo,) { // 文件上传失败回调
          //console.log("文件上传失败: " + uploadInfo.fileData.title);
          uploadInfo.fileData.file.status = 'error';
          handleChange(uploadInfo);
        }
      },
      fileSetting
    );
    file.uploadManager = uploadManager
    if (uploadManager && uploadManager.id) {
      PlvUploaderRef.current.resumeFile(uploadManager.id);
      return true;
    }
    return false;

  }

  const init = () => {
    if (!window.PlvVideoUpload || !getPlvAuth || !refreshPlvAuth) return;
    PlvUploaderRef.current = videoUpload();
    updateUserData(true);
    PlvUploaderRef.current._addFile = PlvUploaderRef.current.addFile;
    PlvUploaderRef.current.addFile = addFile;
  }

  useEffect(() => {
    init();
    return () => {
      clearTimeout(updateTimer.current)
    }
  }, []);

  return { PlvUploaderRef }
}





// const usePlvVideoUpload = () => {
//   const videoUploadInstace = videoUpload();
//   return {videoUpload:videoUploadInstace }
// }
export default ({ onChange }) => {
  const PlvUploaderRef = useRef<any>();
  const updateTimer = useRef<any>();

  const updateUserData = () => {
    PlvUploaderRef.current?.updateUserData(getSignData);
    updateTimer.current = setTimeout(updateUserData, 1000 * 60 * 2)
  }
  const init = () => {
    if (!window.PlvVideoUpload) return;
    PlvUploaderRef.current = videoUpload();
    updateUserData();
  }

  useEffect(() => {
    init();

    return () => {
      clearTimeout(updateTimer.current)
    }
  }, []);


  const [fileList, setFlieList] = useState<any>([]);

  const doUpload = (e) => {
    const files = e.target.files;
    if (files.length > 0) {
      const file = files[0]
      console.log(files[0])
      const fileSetting = { // 文件上传相关信息设置
        title: file.name, // 标题
        desc: 'jssdk插件上传', // 描述
        cataid: '', // 上传分类目录ID
        tag: '', // 标签
        luping: 0, // 是否开启视频课件优化处理，对于上传录屏类视频清晰度有所优化：0为不开启，1为开启
        keepsource: 0, // 是否源文件播放（不对视频进行编码）：0为编码，1为不编码
        state: '' //用户自定义信息，如果提交了该字段，会在服务端上传完成回调时透传返回。
      }
      const uploadManager = PlvUploaderRef.current.addFile(
        file, // file 为待上传的文件对象
        {
          FileStarted: function (uploadInfo) { // 文件开始上传回调
            console.log("文件上传开始: " + uploadInfo.fileData.title);
          },
          FileProgress: function (uploadInfo) { // 文件上传过程返回上传进度信息回调
            console.log("文件上传中: " + (uploadInfo.progress * 100).toFixed(2) + '%');

          },
          FileStopped: function (uploadInfo) { // 文件暂停上传回调
            console.log("文件上传停止: " + uploadInfo.fileData.title);

          },
          FileSucceed: function (uploadInfo) { // 文件上传成功回调
            console.log("文件上传成功: " + uploadInfo.fileData.title);

          },
          FileFailed: function (uploadInfo) { // 文件上传失败回调
            console.log("文件上传失败: " + uploadInfo.fileData.title);
          }
        },
        fileSetting
      );
      file.uploadManager = uploadManager
    }

    setFlieList(e.target.files)
    if (uploadManager && uploadManager.id) {
      PlvUploaderRef.current.resumeFile(uploadManager.id);
    }

  }
  const handleStop = () => {
    PlvUploaderRef.current.stopFile(fileList[0].uploadManager.id)
    console.log(fileList, 222)
  }
  return <div style={{ background: '#fff', height: '100vh' }}>
    <input type="file" onChange={doUpload} />
    <div onClick={handleStop}>停止</div>
  </div>
}